package com.sinosoft.call.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.sinosoft.call.entity.CallConfig;

import com.sinosoft.call.service.CallService;
import com.sinosoft.vo.http.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("fileCallService")
public class FileCallServiceImpl implements CallService{
	private static Pattern p = Pattern.compile("\\{[^\\{]*\\}");
	private HttpHeaders headers;
	@Autowired
	private RestTemplate restTemplate;
	@Override
	public Result callService(CallConfig callConfig, JSON params) {
		JSONObject param = (JSONObject) params;
		String url = getPathValue(callConfig.getCallurl(),param);
		Object file =param.get("base64");
		HttpEntity<?> requestEntity = new HttpEntity<>(file,null);
    	ResponseEntity<String> obj = restTemplate.exchange(url, HttpMethod.valueOf(callConfig.getMenthod()), requestEntity, String.class);
		Object result = obj.getBody();
		return pubResultJSON(true, "", result);
	}
	public HttpHeaders getHttpHeaders() {
		if (headers == null) {
			headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		}
		return headers;
	}
	public String  getPathValue(String url, JSONObject param) {
		String re = url;
		Matcher q = p.matcher(url);
		String key = null;
		while (q.find()) {
			key = q.group(0).replaceAll("\\{|\\}", "");
			re = re.replace("{"+key+"}",param.getString(key));
			param.remove(key);
		}
		return re;
	}
}
